<!-- 过程检验单的首页组件 -->
<template>
  <div class="app-container">
    <!-- 通知栏 -->
    <transition name="notification-fade">
      <div v-if="notificationVisible" class="notification-bar" :class="notificationType">
        <i :class="notificationIcon"></i>
        <span>{{ notificationMessage }}</span>
        <i class="el-icon-close" style="margin-left: 15px; cursor: pointer;" @click="closeNotification"></i>
      </div>
    </transition>
    
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="检验单编号" prop="ipqcCode">
        <el-input
          v-model="queryParams.ipqcCode"
          placeholder="请输入检验单编号"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="检验单名称" prop="ipqcName">
        <el-input
          v-model="queryParams.ipqcName"
          placeholder="请输入检验单名称"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="检测单类型" prop="ipqcType">
        <el-select
          v-model="queryParams.ipqcType"
          placeholder="请选择检测单类型"
          clearable
        >
          <el-option
            v-for="item in ipqcTypeOptions"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="来源单据编号" prop="sourceDocCode">
        <el-input
          v-model="queryParams.sourceDocCode"
          placeholder="请输入来源单据编号"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="工单名称" prop="workOrderName">
        <el-input
          v-model="queryParams.workOrderName"
          placeholder="请输入工单名称"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      
      <el-form-item label="检测结果" prop="checkResult">
        <el-select
          v-model="queryParams.checkResult"
          placeholder="请选择检测结果"
          clearable
        >
          <el-option
            v-for="item in checkResultOptions"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['ldzl-qc:ipqc:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['ldzl-qc:ipqc:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['ldzl-qc:ipqc:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['ldzl-qc:ipqc:export']"
        >导出</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table
      v-loading="loading"
      :data="ipqcList"
      @selection-change="handleSelectionChange"
      border
      size="mini"
      style="width: 100%"
      :row-style="getRowStyle"
      :cell-style="{padding: '0px'}"
      :header-cell-style="{height: '40px', padding: '0px'}"
    >
      <el-table-column type="selection" width="55" align="center" fixed="left" />
      <el-table-column label="检验单序列" align="center" prop="ipqcId" />
      <el-table-column label="检验单编号" align="center" prop="ipqcCode" width="120" fixed="left">
        <template slot-scope="scope">
          <span
            class="clickable-code"
            @click="handleDetail(scope.row)"
            :title="'点击查看详情'"
          >
            {{ scope.row.ipqcCode }}
          </span>
        </template>
      </el-table-column>
      <el-table-column label="检验单名称" align="center" prop="ipqcName" />
      <el-table-column label="检测单类型" align="center" prop="ipqcType" >
        <template slot-scope="scope">
          <el-tag :type="getIpqcTypeTagType(scope.row.ipqcType)">
            {{ formatIpqcType(scope.row.ipqcType) }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="来源单据类型" align="center" prop="sourceDocType">
        <template slot-scope="scope">
          {{ scope.row.sourceDocType === '1' ? '生产任务单' : formatSourceDocType(scope.row.sourceDocType) }}
        </template>
      </el-table-column>
      <el-table-column label="来源单据编号" align="center" prop="sourceDocCode" />
      <el-table-column label="工单编码" align="center" prop="workOrderCode" />
      <el-table-column label="任务编号" align="center" prop="taskCode" />
      <el-table-column label="工序编码" align="center" prop="processCode" />
      <el-table-column label="产品编码" align="center" prop="productCode" />
      <el-table-column label="产品名称" align="center" prop="productName" />
      <el-table-column label="规格型号" align="center" prop="productSfn" />
      <el-table-column label="单位" align="center" prop="unit" />
      <el-table-column label="检测数量" align="center" prop="quantityCheckNum" />
      <el-table-column label="不合格数" align="center" prop="quantityUnqualifiedNum" />
      <el-table-column label="合格品数量" align="center" prop="quantityQualifiedNum" />
      <el-table-column label="检测结果" align="center" prop="checkResult">
        <template slot-scope="scope">
          <el-tag :type="getResultTagType(scope.row.checkResult)">
            {{ formatCheckResult(scope.row.checkResult) }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="检测日期" align="center" prop="inspectDate" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.inspectDate, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="单据状态" align="center" prop="status">
        <template slot-scope="scope">
          <el-tag :type="getStatusTagType(scope.row.status)">
            {{ formatStatus(scope.row.status) }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width" width="250" fixed="right">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-view"
            @click="handleDetail(scope.row)"
          >查看</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['ldzl-qc:ipqc:edit']"
          >修改</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['ldzl-qc:ipqc:remove']"
          >删除</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-warning"
            @click="handleDefectRecord(scope.row)"
            v-hasPermi="['ldzl-qc:ipqc:defect']"
          >缺陷记录</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改过程检验单对话框 -->
    <el-dialog
      :title="title"
      :visible.sync="open"
      width="1220px"
      append-to-body
      :fullscreen="false"
      :close-on-click-modal="false"
      :before-close="cancel"
      class="ipqc-dialog"
      center
    >
      <IpqcForm
        ref="ipqcFormRef"
        :formData="form"
        :type="type"
        @submit="submitForm"
        @cancel="cancel"
        @openInspectPlanDialog="openInspectPlanDialog"
      />
    </el-dialog>

    <!-- 质检方案选择对话框 -->
    <InspectPlanSelector
      :visible.sync="inspectPlanDialogVisible"
      @select="handleSelectInspectPlan"
      @close="closeInspectPlanDialog"
    />

    <!-- 缺陷记录对话框 -->
    <defect-record-dialog
      :visible.sync="defectOpen"
      :title="'缺陷记录 - ' + defectTitle"
      :qcId="defectIpqcId"
      :qcType="'2'"
      :lineId="null"
    />

    <!-- 页面内通知 -->
    <el-dialog
      title="通知"
      :visible.sync="notificationVisible"
      :before-close="() => { this.notificationVisible = false; this.notificationMessage = ''; }"
      width="300px"
      center
    >
      <p>{{ notificationMessage }}</p>
    </el-dialog>
  </div>
</template>

<script>
// 导入缺陷记录组件
import { listIpqc, getIpqc, delIpqc, addIpqc, updateIpqc } from "@/api/qc/ProcesInspection";
import IpqcForm from "./components/IpqcForm";
import InspectPlanSelector from "./components/InspectPlanSelector";
import DefectRecordDialog from "@/views/qc/components/DefectRecordDialog";
import { WebSocketBus } from "@/utils/websocket"; // 导入WebSocket事件总线
import { QcWebSocketBus } from "@/utils/qc-websocket"; // 导入质检WebSocket事件总线

// 是否启用WebSocket功能
const ENABLE_WS_NOTIFICATIONS = true;

export default {
  name: "Ipqc",
  components: {
    IpqcForm,
    InspectPlanSelector,
    DefectRecordDialog
  },
  data() {
    return {
      // 遮罩层
      loading: false,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // IPQC表格数据
      ipqcList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 是否显示质检方案选择对话框
      inspectPlanDialogVisible: false,
      // 缺陷记录对话框
      defectOpen: false,
      defectTitle: "",
      defectIpqcId: null,
      // 表单类型 add/edit
      type: 'add',
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        ipqcCode: null,
        ipqcName: null,
        ipqcType: null,
        sourceDocType: null,
        sourceDocCode: null,
        workOrderName: null,
        factoryName: null,
        checkResult: null,
        status: null,
        productCode: null,
        productName: null,
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        ipqcCode: [
          { required: true, message: "检验单编号不能为空", trigger: "blur" }
        ],
        ipqcType: [
          { required: true, message: "检验类型不能为空", trigger: "change" }
        ],
        sourceDocType: [
          { required: true, message: "来源单据类型不能为空", trigger: "change" }
        ],
        checkResult: [
          { required: true, message: "检测结果不能为空", trigger: "change" }
        ],
        status: [
          { required: true, message: "单据状态不能为空", trigger: "change" }
        ]
      },
      // 选项数据
      ipqcTypeOptions: [
        { value: '1', label: '首检' },
        { value: '2', label: '巡检' },
        { value: '3', label: '产品检测' }
      ],
      sourceDocTypeOptions: [
        { value: '1', label: '生产任务单' },
        { value: '2', label: '来料货检验单' },
        { value: '3', label: '过程检验单' },
        { value: '4', label: '退料检验单' }
      ],
      checkResultOptions: [
        { value: '1', label: '合格' },
        { value: '2', label: '不合格' },
        { value: '3', label: '待检' }
      ],
      statusOptions: [
        { value: '1', label: '草稿' },
        { value: '2', label: '已提交' },
        { value: '3', label: '已审核' }
      ],

      // 待检高亮ID
      highlightId: null,
      
      // WebSocket通知
      notificationVisible: false,
      notificationMessage: "",
      notificationTimer: null,
      notificationType: "info", // 可选值: info, success, warning, error
      notificationIcon: "el-icon-info", // 图标类
      
      // 标记是否从WebSocket通知触发的查询
      fromWebSocketNotification: false
    }
  },
  created() {
    // 检查路由参数，获取检验单编号
    if (this.$route.query.inspectionCode) {
      // 使用检验单编号作为唯一查询条件
      this.queryParams.ipqcCode = this.$route.query.inspectionCode;
      this.fromWebSocketNotification = true; // 标记为从通知触发的查询

      // 清空其他可能干扰查询的条件，确保查询精度
      Object.keys(this.queryParams).forEach(key => {
        if (key !== 'ipqcCode' && key !== 'pageNum' && key !== 'pageSize') {
          this.queryParams[key] = null;
        }
      });

      this.$message.info('正在查找待检测单据，请稍候...');
    }
    this.getList();
    
    // 有条件地注册WebSocket事件处理
    if (ENABLE_WS_NOTIFICATIONS) {
      this.registerWebSocketEvents();
    }
  },
  
  beforeDestroy() {
    // 有条件地移除WebSocket事件监听
    if (ENABLE_WS_NOTIFICATIONS) {
      this.unregisterWebSocketEvents();
    }
    
    // 清除通知计时器
    if (this.notificationTimer) {
      clearTimeout(this.notificationTimer);
    }
  },
  methods: {
    // 注册WebSocket事件
    registerWebSocketEvents() {
      // 监听质检单创建事件 - 新质检WebSocket
      QcWebSocketBus.$on('quality_check_created', this.handleQcInspectionCreated);
      
      // 监听质检单更新事件 - 新质检WebSocket
      QcWebSocketBus.$on('quality_check_updated', this.handleQcInspectionUpdated);
      
      // 监听工作报告生成质检单事件 - 新质检WebSocket
      QcWebSocketBus.$on('work_report_qc_created', this.handleQcWorkReportCreated);
    },
    
    // 移除WebSocket事件监听
    unregisterWebSocketEvents() {
      // 移除新质检WebSocket事件监听
      QcWebSocketBus.$off('quality_check_created', this.handleQcInspectionCreated);
      QcWebSocketBus.$off('quality_check_updated', this.handleQcInspectionUpdated);
      QcWebSocketBus.$off('work_report_qc_created', this.handleQcWorkReportCreated);
    },
    
    // 处理质检单创建通知 - 新质检WebSocket
    handleQcInspectionCreated(data) {
      console.log('收到质检单创建通知:', data);
      // 只处理过程检验类型的通知
      if (data && data.data && data.data.inspectionType === '2') {
        // 显示通知
        this.showNotification(data.message || '新的过程检验单已创建', 'success');
        
        // 设置高亮标记
        if (data.data.inspectionId) {
          this.highlightId = data.data.inspectionId;
          this.fromWebSocketNotification = true;
        }
        
        // 刷新列表
        this.getList();
      }
    },

    // 处理质检单更新通知
    handleQcInspectionUpdated(data) {
        console.log('收到质检单更新通知:', data);
        if (data && data.data && data.data.inspectionType === '2') {
            this.$message.info(`过程检验单 ${data.data.inspectionCode} 已更新`);
            this.highlightId = null; // 更新时清除高亮
            this.getList();
        }
    },
    
    // 处理工作报告生成质检单通知 - 新质检WebSocket
    handleQcWorkReportCreated(data) {
      console.log('收到工作报告生成质检单通知:', data);
      
      // 只处理过程检验类型的通知
      if (data && data.data && data.data.inspectionType === '2') {
        // 显示通知
        this.showNotification(data.message || '报工完成，已生成新的过程检验单，等待审核', 'warning');
        
        // 设置高亮标记
        if (data.data.inspectionId) {
          this.highlightId = data.data.inspectionId;
          this.fromWebSocketNotification = true;
        }
        
        // 刷新列表
        this.getList();
      }
    },

    // 显示页面内通知
    showNotification(message, type = 'info') {
      // 设置通知内容
      this.notificationMessage = message;
      this.notificationVisible = true;
      
      // 设置通知类型和图标
      this.notificationType = type;
      switch(type) {
        case 'success':
          this.notificationIcon = 'el-icon-success';
          break;
        case 'warning':
          this.notificationIcon = 'el-icon-warning';
          break;
        case 'error':
          this.notificationIcon = 'el-icon-error';
          break;
        default:
          this.notificationIcon = 'el-icon-info';
      }
      
      // 5秒后自动隐藏
      if (this.notificationTimer) {
        clearTimeout(this.notificationTimer);
      }
      
      this.notificationTimer = setTimeout(() => {
        this.notificationVisible = false;
      }, 5000);
    },

    /** 查询过程检验单列表 */
    getList() {
      this.loading = true;
      
      // 如果不是从WebSocket通知或特定编号查询触发的查询，则清除高亮
      if (!this.$route.query.inspectionCode && !this.fromWebSocketNotification) {
        this.highlightId = null;
      }
      
      // 重置fromWebSocketNotification标记
      this.fromWebSocketNotification = false;
      
      listIpqc(this.queryParams).then(response => {
        // 确保返回的数据是数组
        this.ipqcList = Array.isArray(response.rows) ? response.rows : [];
        this.total = response.total || 0;

        // 如果使用了检验单编号查询，尝试找到对应记录并高亮显示
        if (this.$route.query.inspectionCode) {
          // 安全检查 - 确保ipqcList是数组且不为空
          if (this.ipqcList && this.ipqcList.length > 0) {
            const foundItem = this.ipqcList.find(item => item && item.ipqcCode === this.$route.query.inspectionCode);
            if (foundItem && foundItem.ipqcId) {
              // 记录ID用于高亮显示
              this.highlightId = foundItem.ipqcId;

              this.$message.success('找到待检测单据，已高亮显示');
              // 滚动到对应行（通过DOM操作，延迟确保表格已渲染）
              this.$nextTick(() => {
                try {
                  const rows = document.querySelectorAll('.el-table__row');
                  if (rows && rows.length > 0) {
                    // 安全遍历行
                    rows.forEach((row, index) => {
                      if (index < this.ipqcList.length &&
                          this.ipqcList[index] &&
                          this.ipqcList[index].ipqcId == this.highlightId) {
                        row.scrollIntoView({ behavior: 'smooth', block: 'center' });
                      }
                    });
                  }
                } catch (error) {
                  console.error('滚动到高亮行时出错:', error);
                }
              });
            } else {
              // 未找到时，给出明确的提示，并提供查询建议
              this.$message.warning({
                message: '未找到指定编号的检验单，请尝试调整查询条件',
                duration: 5000
              });

              // 自动重置查询，重新获取完整列表，便于用户手动查找
              this.$confirm('是否重置查询条件，显示所有检验单?', '提示', {
                confirmButtonText: '是',
                cancelButtonText: '否',
                type: 'info'
              }).then(() => {
                this.resetQuery();
              }).catch(() => {});
            }
          } else {
            this.$message.warning({
              message: '查询结果为空，未找到任何检验单',
              duration: 5000
            });
          }
        }
      }).catch(error => {
        console.error("获取列表失败:", error);
        this.$modal.msgError("数据加载失败");
        this.ipqcList = []; // 确保发生错误时列表被重置为空数组
      }).finally(() => {
        this.loading = false;
      });
    },

    // 格式化方法
    formatSourceDocType(type) {
      const map = {
        '1': '生产任务单',
        '2': '来料货检验单',
        '3': '过程检验单',
        '4': '退料检验单'
      }
      return map[type] || type
    },

    formatCheckResult(result) {
      const map = {
        '1': '合格',
        '2': '不合格',
        '3': '待检'
      }
      return map[result] || result
    },

    formatStatus(status) {
      const map = {
        '1': '草稿',
        '2': '已提交',
        '3': '已审核'
      }
      return map[status] || status
    },

    // 获取标签类型方法
    getSourceDocTypeTagType(type) {
      const map = {
        '1': '',
        '2': 'info',
        '3': 'primary',
        '4': 'warning',
        '5': 'danger'
      }
      return map[type] || ''
    },

    getResultTagType(result) {
      const map = {
        '1': 'success',
        '2': 'danger',
        '3': 'warning'
      }
      return map[result] || ''
    },

    getStatusTagType(status) {
      const map = {
        '1': 'info',
        '2': 'primary',
        '3': 'success'
      }
      return map[status] || ''
    },

    formatIpqcType(type) {
      const map = {
        '1': '首检',
        '2': '巡检',
        '3': '产品检测'
      }
      return map[type] || type
    },

    getIpqcTypeTagType(type) {
      const map = {
        '1': 'info',
        '2': 'success',
        '3': 'primary',
        '4': 'warning'
      }
      return map[type] || ''
    },

    cancel() {
      this.open = false
      this.reset()
    },

    // 表单提交
    submitForm(formData) {
      this.$modal.loading("正在提交数据，请稍候...");
      if (this.form.ipqcId != null) {
        updateIpqc(formData).then(response => {
          this.$modal.closeLoading();
          this.$modal.msgSuccess("修改成功");
          this.open = false;
          this.highlightId = null; // 编辑完成后清除高亮ID
          this.getList();
        }).catch(() => {
          this.$modal.closeLoading();
        });
      } else {
        addIpqc(formData).then(response => {
          this.$modal.closeLoading();
          this.$modal.msgSuccess("新增成功");
          this.open = false;
          this.getList();
        }).catch(() => {
          this.$modal.closeLoading();
        });
      }
    },

    // 打开质检方案选择对话框
    openInspectPlanDialog() {
      this.inspectPlanDialogVisible = true;
    },

    // 关闭质检方案选择对话框
    closeInspectPlanDialog() {
      this.inspectPlanDialogVisible = false;
    },

    // 选择质检方案
    handleSelectInspectPlan(plan) {
      if (this.$refs.ipqcFormRef) {
        this.$refs.ipqcFormRef.selectInspectPlan(plan);
      }
    },

    reset() {
      this.form = {
        ipqcId: null,
        ipqcCode: null,
        ipqcName: null,
        ipqcType: null,
        sourceDocType: null,
        sourceDocCode: null,
        workOrderCode: null,
        workOrderName: null,
        taskCode: null,
        factoryCode: null,
        factoryName: null,
        processCode: null,
        productId: null,
        productCode: null,
        productName: null,
        productSfn: null,
        unit: null,
        quantityCheckNum: 0,
        quantityUnqualifiedNum: 0,
        quantityQualifiedNum: 0,
        checkResult: null,
        status: '1',
        inspectDate: new Date().toISOString().split('T')[0],
        remark: null
      };
      // 重置表单，在组件中进行
      if (this.$refs.ipqcFormRef) {
        this.$refs.ipqcFormRef.resetForm();
      }
    },

    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      // 清除高亮ID，因为用户主动搜索了
      this.highlightId = null;
      this.getList();
    },

    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      // 清除高亮ID
      this.highlightId = null;
      this.handleQuery();
    },

    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.ipqcId)
      this.single = selection.length !== 1
      this.multiple = !selection.length
    },

    handleAdd() {
      this.reset()
      this.type = "add"
      this.open = true
      this.title = "添加过程检验单"
    },

    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const ipqcId = row.ipqcId || this.ids;

      // 清除高亮状态，因为要进入修改模式
      this.highlightId = null;

      getIpqc(ipqcId).then(response => {
        this.form = response.data;

        // 重要：检查并确保inspectPlanId存在
        // 后端返回的是templateId而不是inspectPlanId，需要映射
        if (!this.form.inspectPlanId && this.form.templateId) {
          console.log('修改数据中发现templateId，映射到inspectPlanId:', this.form.templateId);
          this.form.inspectPlanId = this.form.templateId;
        }

        // 打印日志以便调试
        console.log('修改数据:', this.form);
        console.log('质检方案ID:', this.form.inspectPlanId);
        console.log('质检方案名称:', this.form.inspectPlanName);
        console.log('模板ID(templateId):', this.form.templateId);

        this.type = "edit";
        this.open = true;
        this.title = "修改过程检验单";
      });
    },

    handleDelete(row) {
      const rqc = row || {};
      const ipqcIds = row.ipqcId || this.ids
      

      // 检查检测结果是否为待检
      if (rqc.checkResult !== 3 && rqc.checkResult !== '3') {
        this.$modal.msgError("只能删除检测结果为待检的单据");
        return;
      }
      this.$modal.confirm('是否确认删除过程检验单编号为"' + ipqcIds + '"的数据项？').then(() => {
        return delIpqc(ipqcIds)
      }).then(() => {
        this.getList()
        this.$modal.msgSuccess("删除成功")
      }).catch(() => {})
    },

    handleExport() {
      this.download('ldzl-qc/ipqc/export', {
        ...this.queryParams
      }, `ipqc_${new Date().getTime()}.xlsx`)
    },

    handleDetail(row) {
      if (!row || !row.ipqcId) {
        this.$modal.msgError("请选择有效的检测单");
        return;
      }

      console.log('准备跳转到详情页，ID:', row.ipqcId);
      this.$router.push(`/qc/ProcesInspection/detail/${row.ipqcId}`);
    },

    /** 缺陷记录按钮操作 */
    handleDefectRecord(row) {
      if (!row || !row.ipqcId) {
        this.$modal.msgError("请选择有效的检测单");
        return;
      }

      // 设置ID和标题
      this.defectIpqcId = row.ipqcId;
      this.defectTitle = row.ipqcCode || '';

      // 打开对话框
      this.defectOpen = true;
    },

    // 获取行样式
    getRowStyle(row) {
      const baseStyle = {height: '40px'};
      // 确保row和row.row存在且有效
      if (this.highlightId && row && row.row && row.row.ipqcId == this.highlightId) {
        return {
          ...baseStyle,
          backgroundColor: '#fdf5e6', // 淡黄色背景
          fontWeight: 'bold',
          color: '#ff7800'
        };
      }
      return baseStyle;
    },

    // 关闭通知栏
    closeNotification() {
      this.notificationVisible = false;
      this.notificationMessage = "";
    }
  }
}
</script>

<style scoped>
/* 可以添加一些自定义样式 */
::v-deep .ipqc-dialog {
  display: flex;
  flex-direction: column;
  height: 820px !important; /* 固定对话框高度 */
  overflow: hidden;
}

::v-deep .ipqc-dialog .el-dialog {
  height: 820px !important;
  margin-top: 5vh !important;
}

::v-deep .ipqc-dialog .el-dialog__header {
  padding: 10px 15px;
  border-bottom: 1px solid #e9e9e9;
}

::v-deep .ipqc-dialog .el-dialog__body {
  padding: 0;
  height: calc(100% - 55px) !important;
  overflow: hidden;
}

.clickable-code {
  color: #409EFF;
  cursor: pointer;
  text-decoration: underline;
  font-weight: bold;
}

.clickable-code:hover {
  color: #66b1ff;
}

.clickable-code:active {
  color: #3a8ee6;
}

/* 优化固定列样式 */
::v-deep .el-table__fixed-right {
  height: 100% !important;
}

::v-deep .el-table__fixed-left {
  height: 100% !important;
}

::v-deep .el-table__row td {
  height: 40px !important;
}

/* 确保所有单元格内容垂直居中 */
::v-deep .el-table .cell {
  display: flex;
  align-items: center;
  justify-content: center;
  height: 100%;
}

/* 调整按钮单元格内容样式 */
::v-deep .el-table .cell .el-button {
  padding: 3px 0;
  margin: 0 3px;
}

/* 高亮待检行样式 */
.highlight-row {
  background-color: #fdf5e6 !important;
  font-weight: bold;
  color: #ff7800;
}

/* 顶部通知栏样式 */
.notification-bar {
  position: fixed;
  top: 70px;
  left: 50%;
  transform: translateX(-50%);
  z-index: 9999;
  padding: 10px 20px;
  background-color: #ecf8ff;
  border-left: 5px solid #50bfff;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
  border-radius: 4px;
  font-size: 14px;
  display: flex;
  align-items: center;
  transition: all 0.3s;
}

.notification-bar i {
  margin-right: 10px;
  font-size: 20px;
  color: #50bfff;
}

.notification-bar.success {
  background-color: #f0f9eb;
  border-left-color: #67c23a;
}

.notification-bar.success i {
  color: #67c23a;
}

.notification-bar.warning {
  background-color: #fdf6ec;
  border-left-color: #e6a23c;
}

.notification-bar.warning i {
  color: #e6a23c;
}

.notification-bar.error {
  background-color: #fef0f0;
  border-left-color: #f56c6c;
}

.notification-bar.error i {
  color: #f56c6c;
}

/* 通知显示动画 */
.notification-fade-enter-active, .notification-fade-leave-active {
  transition: opacity 0.5s, transform 0.5s;
}
.notification-fade-enter, .notification-fade-leave-to {
  opacity: 0;
  transform: translateX(-50%) translateY(-20px);
}
</style>
